


const mongoose = require('mongoose');

var express = require('express')
// 注意这里的声明
var company = express()

const model = require("../../dao/model/model");
const {createResponse}= require("../../util/createResponse/index");
const {businessCodes}= require("../../code/businessCodes/index");
const {companyService } = require('../../service/impl/companyService/index');
const {userRolesService } = require('../../service/impl/userRolesService/index');
const {auth_service} = require('../../service/impl/auth_service/index');
const {role_service} = require('../../service/impl/role_service/index');
const {auth_code}= require('../../code/auth_code/index');
const multer = require('multer');
const path = require('path');


// const storage = multer.diskStorage({
//   // 保存的目录,uploads,就是项目跟目录的uploads,文件会保存到这里
//   destination: function (req, file, cb) {
//     cb(null, 'uploads')
//   },
//   // 定义文件名,注意,cb,file.originalname,因为默认是不带后缀名的,我这里改成了这个,就默认带后缀名
//   filename: function (req, file, cb) {
//     const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
//     cb(null,uniqueSuffix + file.originalname)
//   }
// })
// // 图片服务
// const upload = multer({ storage: storage })
// multer 配置


  
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 文件保存的目录
    cb(null, 'uploads/companyCertification/');
  },
  filename: function (req, file, cb){
    // 文件名： 公司名称 + 地址 + 时间戳 + 1E9范围内随机数 + 文件扩展名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = file ? path.extname(file.originalname) : '.jpg';
  
    const companyName = req.body.company_name ? req.body.company_name.split(' ').join('_') : 'default_company';
    const address = req.body.company_detail_position ? req.body.company_detail_position.split(' ').join('_') : 'default_position';
  
    cb(null, `${companyName}-${address}-${uniqueSuffix}${ext}`);
  }
});
  
const upload = multer({ storage: storage });


company.post('/post/company/add', upload.single('file'), async (req,res) => {
  let result 
  try {
    let roleObj =  await role_service.getIns().findOne({"roleName_str":"企业超级管理员"})
    let news = {
      publisherID: req.body.news.publisherID,
      company_name: req.body.news.company_name,
      company_desc: req.body.news.company_desc,
      company_position: req.body.news.company_position,
      company_detail_position: req.body.news.company_detail_position,
       store_src: req?.file?.path,
      auth_userID: {
        auth_userID: req.body.news.publisherID,
        auth_role: roleObj
      }
    }
    result =  await companyService.getIns().create(news)
  } catch (error) {
    console.log(error);
    createResponse(res,500,businessCodes.b2)
    return
  }
    createResponse(res,200,businessCodes.b1,result)
  })
  
  company.post('/post/company/delete', async (req,res) => {
    let result
    try {
      let  id  = req.body.conditions.id
      result =  await companyService.getIns().findByIdAndDelete(id)
    } catch (error) {
      console.log(error);
      createResponse(res,500,businessCodes.b2)
      return
    }
    createResponse(res,200,businessCodes.b1,result)
  })
  
  company.post('/post/company/update', async (req,res) => {
    let result
    try {
      let  id  = req.body.conditions.id
      let updates = req.body.updates
      result =  await companyService.getIns().findByIdAndUpdate(id,updates)
    } catch (error) {
      console.log(error);
      createResponse(res,500,businessCodes.b2)
      return
    }
    createResponse(res,200,businessCodes.b1,result)
  })
  
  company.post('/post/company/query', async (req,res) => {
    let result
    try {
      result =  await companyService.getIns().find()
    } catch (error) {
      console.log(error);
      createResponse(res,500,businessCodes.b2)
      return
    }
    createResponse(res,200,businessCodes.b1,result)
  })


  // 根据用户id,查询该用户的团队
  company.post('/post/company/queryTeamByUserID', async (req,res) => {
    let result
    console.log(req.body.conditions.auth_userID,555);
    try {
      result =  await companyService.getIns().find({
        "auth_userID.auth_userID": req.body.conditions.auth_userID
      })
    } catch (error) {
      console.log(error);
      createResponse(res,500,businessCodes.b2)
      return
    }
    createResponse(res,200,businessCodes.b1,result)
  })


  // 删除指定公司的指定用户
  company.post('/post/company/deleteCompanyUser', async (req,res) => {
    let result
    try {
      let companyID = req.body.conditions.companyID;
      let auth_userID = req.body.conditions.auth_userID;
      result =   await companyService.getIns().findByIdAndUpdate(
        companyID,
        {
          $pull: {
            auth_userID: {
                auth_userID: auth_userID
            }
        }
        }
      );
    } catch (error) {
      console.log(error);
      createResponse(res,500,businessCodes.b2)
      return
    }
    createResponse(res,200,businessCodes.b1,result)
  })
  
  module.exports= company

  /* 
  router.post('/post/company/add', upload.single('avatar'), (req,res) => {
  controller.company_controller.getSigleIns().create(req,res)
})

router.post('/post/company/delete', (req,res) => {
  controller.company_controller.getSigleIns().findByIdAndRemove(req,res)
})


router.post('/post/company/update', (req,res) => {
  controller.company_controller.getSigleIns().findByIdAndUpdate(req,res)
})

// 修改该企业的审核状态,并把发布用户添加到该公司的超级管理员
router.post('/post/company/updateAndAddSuperManager', (req,res) => {
  controller.company_controller.getSigleIns().findByIdAndUpdateAndAddsuperManager(req,res)
})

router.post('/post/company/queryAll', (req,res) => {
  controller.company_controller.getSigleIns().queryAll(req,res)
})
  */



/* 
company.post('/post/company/add', upload.single('file'), async (req,res) => {
  let result 
  try {
    let roleObj =  await role_service.getIns().findOne({"roleName_str":"企业超级管理员"})
    let news = {
      publisherID: req.body.news.publisherID,
      company_name: req.body.news.company_name,
      company_desc: req.body.news.company_desc,
      company_position: req.body.news.company_position,
      company_detail_position: req.body.news.company_detail_position,
      store_src: req.file.path,
      auth_userID: {
        auth_userID: req.body.news.publisherID,
        auth_role: roleObj
      }
    }
    result =  await companyService.getIns().create(news)
    if(result){
      let authObj =   await auth_service.getIns().findOne({"auth_number":"auth002"})
        //给userRolesService 添加对应权限
        let conditions = {
          "userID": result.publisherID,
        }
        let updates = {
          $push:{
                "appDynamicsAuths_arr":
                    {
                      "authID": authObj._id,
                      "authEnable_bol": true
                    },
                "companyRoles_arr":{
                        "companyID":result._id,
                        "roleID":roleObj._id
                    } 
                }
         }

        // 首先用 $set 操作符来确保该用户的记录存在
        let userRolesDoc = await userRolesService.getIns().findOneAndUpdate(
          conditions,
          { $setOnInsert: { "userID": result.publisherID, "appDynamicsAuths_arr": [] }},
          { new: true, upsert: true } 
        );

       

        // 然后更新 appDynamicsAuths_arr 字段
        let conditions2 = {
          "userID": result.publisherID,
          "appDynamicsAuths_arr": {
            $elemMatch: {
              "authID": authObj._id,
              "authEnable_bol": true
            }
          }
        }

        // 更新公司角色
        
        // 更新用户的团队进入权限
        let dd = await userRolesService.getIns().findOne(conditions2)
        result = result.toObject() 
          // 这里是1好 conditions  ,
          let oo  = await userRolesService.getIns().findOneAndUpdate(conditions,updates,{
            returnOriginal: false
          })
          result.userRoles = dd
  
           result.userRoles = oo
    }
  } catch (error) {
    console.log(error);
    createResponse(res,500,businessCodes.b2)
    return
  }
    createResponse(res,200,businessCodes.b1,result)
  })

*/